<script setup lang="ts">
import { scrollTo } from '@fl/utils/scroll-to'

const props = defineProps({
    autoScroll: {
        default: true,
        type: Boolean,
    },
    background: {
        default: true,
        type: Boolean,
    },
    hidden: {
        default: false,
        type: Boolean,
    },
    layout: {
        default: 'total, sizes, prev, pager, next, jumper',
        type: String,
    },
    limit: {
        default: 20,
        type: Number,
    },
    page: {
        default: 1,
        type: Number,
    },
    pageSizes: {
        default() {
            return [10, 20, 30, 50]
        },
        type: Array<number>,
    },
    // 移动端页码按钮的数量端默认值5
    pagerCount: {
        default: document.body.clientWidth < 992 ? 5 : 7,
        type: Number,
    },
    total: {
        required: true,
        type: Number,
    },
})

const emit = defineEmits(['update:page', 'pagination', 'update:limit'])
const currentPage = computed({
    get() {
        return props.page
    },
    set(val) {
        emit('update:page', val)
    },
})
const pageSize = computed({
    get() {
        return props.limit
    },
    set(val) {
        emit('update:limit', val)
    },
})
function handleSizeChange(val) {
    if (currentPage.value * val > props.total) {
        currentPage.value = 1
    }
    emit('pagination', { limit: val, page: currentPage.value })
    if (props.autoScroll) {
        scrollTo(0, 800)
    }
}
function handleCurrentChange(val) {
    emit('pagination', { limit: pageSize.value, page: val })
    if (props.autoScroll) {
        scrollTo(0, 800)
    }
}
</script>

<template>
    <div :class="{ hidden }"
         class="pagination-container"
    >
        <el-pagination v-model:current-page="currentPage"
                       v-model:page-size="pageSize"
                       :background="background"
                       :layout="layout"
                       :page-sizes="pageSizes"
                       :pager-count="pagerCount"
                       :total="total"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
        />
    </div>
</template>

<style scoped lang="scss">
.pagination-container {
    background: #fff;
    padding: 32px 16px;
}
.pagination-container.hidden {
    display: none;
}
</style>
